<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>课程管理</el-breadcrumb-item>
    <el-breadcrumb-item>课程信息管理</el-breadcrumb-item>
  </el-breadcrumb>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="课程名称:">
        <el-input v-model="formInline.courseName" placeholder="请输入课程名称" clearable :suffix-icon="Search" @clear="handleClear" />
      </el-form-item>
      <el-form-item label="课程分类:">
        <el-select
            v-model="formInline.courseClassifyId"
            placeholder="请选择"
            style="width: 240px"
            clearable
            @clear="handleClear"
        >
          <el-option
              v-for="item in kecheng"
              :key="item.id"
              :label="item.classifyName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="心理师名称:">
        <el-select
            v-model="formInline.counselorId"
            placeholder="请选择心理师"
            style="width: 240px"
            clearable
            @clear="handleClear"
        >
          <el-option
              v-for="item in counselors"
              :key="item.id"
              :label="item.counselorName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button type="primary" @click="addbutton">新增课程</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
    <el-table-column type="selection" fixed prop="id" label="ID" width="50" />
    <el-table-column prop="id" label="课程id" width="80" />
    <el-table-column prop="courseName" label="课程名称" width="120" />
    <!-- 课程图片列 -->
    <el-table-column prop="simplifyImage" label="课程图片" width="200">
      <template #default="scope">
        <img
            :src="'http://localhost:8080' + scope.row.simplifyImage"
            alt="课程图片"
            style="width: 100px; height: 100px; border: 1px solid #f5f7fa; background-color: #f5f7fa; object-fit: contain"
        >
      </template>
    </el-table-column>
    <el-table-column prop="courseTime" label="时长" width="55" />
    <el-table-column prop="videoNumber" label="数量" width="55" />
    <el-table-column prop="studyNumber" label="学习量" width="80" />
    <el-table-column prop="courseIntro" label="简介" width="720" />
    <el-table-column prop="discountPrice" label="价格" width="60" />
    <el-table-column prop="courseClassify.classifyName" label="分类" width="150" />
    <el-table-column prop="counselor.counselorName" label="心理导师名" width="110" />
    <el-table-column fixed="right" label="操作" min-width="150">
      <template #default="scope">
        <el-button type="primary" size="small" @click="bianji(scope.row)">编辑</el-button>
        <el-button type="danger" size="small" @click="remove(scope.row.id)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
  <!-- 新增/编辑课程弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
    <el-form>
      <el-form-item label="课程名称" :label-width="formLabelWidth">
        <el-input v-model="form.courseName" autocomplete="off" placeholder="请输入课程名称" />
      </el-form-item>

      <!-- 课程图片上传（不显示文字） -->
      <el-form-item label="课程图片" :label-width="formLabelWidth">
        <el-upload
            action="http://localhost:8080/upload"
            list-type="picture-card"
            :on-success="handleSuccess"
            :limit="1"
            :on-preview="handlePictureCardPreview"
            :file-list="fileList"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
            class="upload-no-text"
        >
          <el-icon style="width: 128px; height: 128px; border: 1px dashed #DCDFE6; border-radius: 5px; font-size: 24px; display: flex; align-items: center; justify-content: center;">
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img :src="dialogImageUrl" alt="预览图片" style="width: 100%" />
        </el-dialog>
      </el-form-item>


      <el-form-item label="适用人群" :label-width="formLabelWidth">
        <el-input v-model="form.suitPerson" autocomplete="off" placeholder="请输入适用人群" />
      </el-form-item>
      <el-form-item label="学习收获" :label-width="formLabelWidth">
        <el-input v-model="form.learningGains" autocomplete="off" placeholder="请输入学习收获" />
      </el-form-item>
      <el-form-item label="订阅须知" :label-width="formLabelWidth">
        <el-input v-model="form.subscription" autocomplete="off" placeholder="请输入订阅须知" />
      </el-form-item>
      <el-form-item label="课程价格" :label-width="formLabelWidth">
        <el-input v-model="form.discountPrice" autocomplete="off" placeholder="请输入课程价格" />
      </el-form-item>
      <el-form-item label="心理师名称" :label-width="formLabelWidth">
        <el-select
            v-model="form.counselorId"
            placeholder="请选择心理师"
            style="width: 240px"
            clearable
        >
          <el-option
              v-for="item in counselors"
              :key="item.id"
              :label="item.counselorName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程分类" :label-width="formLabelWidth">
        <el-select
            v-model="form.courseClassifyId"
            placeholder="请选择"
            style="width: 240px"
            clearable
        >
          <el-option
              v-for="item in kecheng"
              :key="item.id"
              :label="item.classifyName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程简介" :label-width="formLabelWidth">
        <el-input v-model="form.courseIntro" autocomplete="off" placeholder="请输入课程简介" />
      </el-form-item>

      <!-- 仅在编辑时显示课程时长和视频数量 -->
      <el-form-item v-if="dialogTitle === '修改课程'" label="课程时长" :label-width="formLabelWidth">
        <el-input v-model="form.courseTime" autocomplete="off" placeholder="请输入课程时长" />
      </el-form-item>
      <el-form-item v-if="dialogTitle === '修改课程'" label="视频数量" :label-width="formLabelWidth">
        <el-input v-model="form.videoNumber" autocomplete="off" placeholder="请输入视频数量" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogTitle === '新增课程' ? add() : update()">
          {{ dialogTitle === '新增课程' ? '确认' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表单相关配置
const formLabelWidth = '120px'
const dialogTitle = ref('新增课程')
const dialogFormVisible = ref(false)
const currentId = ref(0) // 存储当前编辑的课程ID

// 图片上传相关配置
const MAX_FILE_SIZE_MB = 10  // 最大文件大小限制(MB)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])

// 表单数据
const form = ref({
  courseName: '',
  courseTime: '',       // 编辑时使用
  videoNumber: '',      // 编辑时使用
  suitPerson: '',
  learningGains: '',
  subscription: '',
  discountPrice: '',
  courseIntro: '',
  courseClassifyId: '',
  counselorId: '',
  simplifyImage: ''
})

// 搜索表单
const formInline = reactive({
  courseName: '',
  courseClassifyId: '',
  counselorId: '',
  pageSize: 10,
  pageNum: 1,
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])
const kecheng = ref([])
const counselors = ref([]) // 存储心理师数据

// 初始化加载
onMounted(() => {
  // 获取课程分类
  axios
      .get('http://localhost:8080/courseclassify')
      .then((response) => {
        if (response.data.code === 200) {
          kecheng.value = response.data.data
        }
      })
  // 获取心理师数据
  axios
      .get('http://localhost:8080/counselor1')
      .then((response) => {
        if (response.data.code === 200) {
          counselors.value = response.data.data
        }
      })
  // 加载表格数据
  query()
})

// 获取表格数据
const query = () => {
  // 构建查询参数
  const params = new URLSearchParams()
  params.append('pageSize', pageSize.value)
  params.append('pageNum', currentPage.value)
  if (formInline.courseName) params.append('courseName', formInline.courseName)
  if (formInline.courseClassifyId) params.append('courseClassifyId', formInline.courseClassifyId)
  if (formInline.counselorId) params.append('counselorId', formInline.counselorId)

  axios
      .get(`http://localhost:8080/course/page?${params.toString()}`)
      .then((response) => {
        tableData.value = response.data.data.list
        total.value = response.data.data.total
      })
      .catch((error) => {
        console.log('获取表格数据失败：', error)
        ElMessage.error('获取数据失败，请稍后重试')
      })
}

// 搜索功能
const onSubmit = () => {
  currentPage.value = 1
  query()
}

// 新增课程
const addbutton = () => {
  dialogTitle.value = '新增课程'
  // 重置表单
  form.value = {
    courseName: '',
    courseTime: '',
    videoNumber: '',
    suitPerson: '',
    learningGains: '',
    subscription: '',
    discountPrice: '',
    courseIntro: '',
    courseClassifyId: '',
    counselorId: '',
    simplifyImage: ''
  }
  fileList.value = []
  dialogFormVisible.value = true
}

// 提交新增
const add = () => {
  // 验证图片是否上传
  if (!form.value.simplifyImage) {
    return ElMessage.warning('请上传课程图片')
  }

  // 验证必要字段
  if (!form.value.courseName) {
    return ElMessage.warning('请输入课程名称')
  }
  if (!form.value.discountPrice) {
    return ElMessage.warning('请输入课程价格')
  }

  // 转换数值类型
  const submitData = {
    ...form.value,
    discountPrice: Number(form.value.discountPrice),
    courseTime: form.value.courseTime ? Number(form.value.courseTime) : 0,
    videoNumber: form.value.videoNumber ? Number(form.value.videoNumber) : 0
  }

  axios
      .post('http://localhost:8080/course', submitData)
      .then((response) => {
        if (response.data.code === 200) {
          ElMessage({ type: 'success', message: '新增成功' })
          dialogFormVisible.value = false
          query()
        } else {
          ElMessage({ type: 'error', message: '新增失败: ' + response.data.message })
        }
      })
      .catch((error) => {
        ElMessage({ type: 'error', message: '新增请求失败' })
        console.log('新增请求失败详情：', error)
      })
}

// 编辑课程
const bianji = (row) => {
  dialogTitle.value = '修改课程'
  currentId.value = row.id
  // 填充表单数据
  form.value = {
    courseName: row.courseName || '',
    courseTime: row.courseTime || '',
    videoNumber: row.videoNumber || '',
    suitPerson: row.suitPerson || '',
    learningGains: row.learningGains || '',
    subscription: row.subscription || '',
    discountPrice: row.discountPrice || '',
    courseIntro: row.courseIntro || '',
    courseClassifyId: row.courseClassify?.id || '',
    counselorId: row.counselor?.id || '',
    simplifyImage: row.simplifyImage || ''
  }
  // 回显已上传的图片
  fileList.value = row.simplifyImage
      ? [{ url: `http://localhost:8080${row.simplifyImage}` }]
      : []
  dialogFormVisible.value = true
}

// 提交更新
const update = () => {
  // 验证图片是否存在
  if (!form.value.simplifyImage) {
    return ElMessage.warning('请上传课程图片')
  }

  // 验证必要字段
  if (!form.value.courseName) {
    return ElMessage.warning('请输入课程名称')
  }
  if (!form.value.courseTime) {
    return ElMessage.warning('请输入课程时长')
  }
  if (!form.value.videoNumber) {
    return ElMessage.warning('请输入视频数量')
  }
  if (!form.value.discountPrice) {
    return ElMessage.warning('请输入课程价格')
  }

  // 转换数值类型
  const submitData = {
    ...form.value,
    id: currentId.value,
    courseTime: Number(form.value.courseTime),
    videoNumber: Number(form.value.videoNumber),
    discountPrice: Number(form.value.discountPrice)
  }

  axios
      .put(`http://localhost:8080/course`, submitData)
      .then((response) => {
        if (response.data.code === 200) {
          ElMessage({ type: 'success', message: '更新成功' })
          dialogFormVisible.value = false
          query()
        } else {
          ElMessage({ type: 'error', message: '更新失败: ' + response.data.message })
        }
      })
      .catch((error) => {
        ElMessage({ type: 'error', message: '更新请求失败' })
        console.log('更新请求失败详情：', error)
      })
}

// 删除课程
const remove = (id) => {
  ElMessageBox.confirm('请确认是否删除?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        axios
            .delete(`http://localhost:8080/course/${id}`)
            .then((response) => {
              if (response.data.code === 200) {
                ElMessage({ type: 'success', message: '删除成功' })
                query()
              } else {
                ElMessage({ type: 'error', message: '删除失败' })
              }
            })
            .catch((error) => {
              ElMessage({ type: 'error', message: '删除请求失败' })
              console.log('删除请求失败详情：', error)
            })
      })
      .catch(() => {
        ElMessage({ type: 'info', message: '取消删除' })
      })
}

// 批量删除
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessageBox.alert('至少选择一条数据才能进行删除', '提示')
    return
  }

  const ids = selectedRows.value.map((row) => row.id).join(',')
  ElMessageBox.confirm(
      `确定要删除选中的${selectedRows.value.length}条数据吗?`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios
            .delete(`http://localhost:8080/course?ids=${ids}`)
            .then((response) => {
              if (response.data.code === 200) {
                ElMessage({ type: 'success', message: '删除成功' })
                query()
              } else {
                ElMessage({ type: 'error', message: '删除失败' })
              }
            })
            .catch((error) => {
              ElMessage({ type: 'error', message: '删除请求失败' })
              console.log('批量删除请求失败详情：', error)
            })
      })
      .catch(() => {
        ElMessage({ type: 'info', message: '取消删除' })
      })
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  query()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}

// 选择项变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 清空搜索
const handleClear = () => {
  formInline.courseName = ''
  formInline.courseClassifyId = ''
  formInline.counselorId = ''
  query()
}

// 图片上传成功处理
const handleSuccess = (res, file) => {
  form.value.simplifyImage = res.data
  fileList.value = [{ url: `http://localhost:8080${res.data}` }]
}

// 移除图片处理
const handleRemove = (file, fileList) => {
  form.value.simplifyImage = ''
}

// 图片预览处理
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 图片上传前校验（支持多种格式，最大10MB）
const beforeAvatarUpload = (rawFile) => {
  const allowedTypes = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/webp',
    'image/bmp',
    'image/svg+xml'
  ]

  const isAllowed = allowedTypes.includes(rawFile.type)
  // 计算10MB的字节数：10 * 1024KB * 1024B
  const maxSizeBytes = MAX_FILE_SIZE_MB * 1024 * 1024
  const isLt10M = rawFile.size <= maxSizeBytes

  if (!isAllowed) {
    ElMessage.error('上传图片格式不支持，请上传JPG、PNG、GIF、WebP、BMP或SVG格式!')
  }
  if (!isLt10M) {
    ElMessage.error(`上传图片大小不能超过 ${MAX_FILE_SIZE_MB}MB!`)
  }
  return isAllowed && isLt10M
}
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-table-column {
  max-height: 150px;
}

.el-breadcrumb {
  border-bottom: 1px solid #eeeeee;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

/* 隐藏上传组件的文字说明 */
.upload-no-text .el-upload__text {
  display: none;
}

/* 优化上传按钮样式 */
.upload-no-text .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.upload-no-text .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>
